@page "/visitor/checkin"


@using Blazor.Server.UI.Services
@using Blazor.Server.UI.Pages.CheckinPoints
@using CleanArchitecture.Blazor.Application.Features.VisitorHistories.Commands.Create
@using CleanArchitecture.Blazor.Application.Features.VisitorHistories.DTOs
@using CleanArchitecture.Blazor.Application.Features.VisitorHistories.Queries.GetAll
@using CleanArchitecture.Blazor.Application.Features.Visitors.Commands.Create
@using CleanArchitecture.Blazor.Application.Features.Visitors.Commands.Delete
@using CleanArchitecture.Blazor.Application.Features.Visitors.Constant
@using CleanArchitecture.Blazor.Application.Features.Visitors.DTOs
@using CleanArchitecture.Blazor.Application.Features.Visitors.Queries.Pagination
@using CleanArchitecture.Blazor.Application.Features.Visitors.Commands.AddEdit
@using CleanArchitecture.Blazor.Application.Features.Visitors.Queries.Search
@using HashidsNet
@using Net.Codecrete.QrCodeGenerator
@using SixLabors.Fonts;
@using SixLabors.ImageSharp;
@using SixLabors.ImageSharp.Drawing;
@using SixLabors.ImageSharp.Drawing.Processing;
@using SixLabors.ImageSharp.Formats.Jpeg
@using SixLabors.ImageSharp.PixelFormats;
@using SixLabors.ImageSharp.Processing;
@inject IJSRuntime JS
@inject IStringLocalizer<Visitors> L
@attribute [Authorize(Policy = Permissions.Visitors.Checkin)]
<PageTitle>@Title</PageTitle>
<style>
    .mud-table-toolbar {
        height: 84px !important;
    }
</style>
<ErrorBoundary>
    <ChildContent>
        <MudGrid>
            <MudItem xs="12" sm="5">
                <div class="d-flex justify-center align-content-center">
                    <MudCard Style="width:320px">
                        <div id="my_camera" class="mud-card-media pa-0 ma-0" style="width:320px; height:240px;"></div>
                        <MudCardActions Style="height:45px">
                            <MudButton Variant="Variant.Text" OnClick="TakePhoto" Color="MudBlazor.Color.Primary"></MudButton>
                        </MudCardActions>
                    </MudCard>
                </div>
            </MudItem>


            <MudItem xs="12" sm="5">
                <div class="d-flex flex-column">
                    <MudTabs Class="align-self-center" Style="width:320px" Elevation="25" Color="MudBlazor.Color.Transparent" Rounded="true" Centered="true" PanelClass="mt-6">
                        <MudTabPanel Text="@L["Check-in"]">
                            @if (_notfound)
                            {
                                <MudAlert Severity="MudBlazor.Severity.Error">@L["Not found visitor"]</MudAlert>
                            }
                            @if (_visitor is not null && _visitor.Status != VisitorStatus.PendingCheckin)
                            {
                                <MudAlert Severity="MudBlazor.Severity.Error">@L[string.Format("Visitor current status is {0}",_visitor.Status)]</MudAlert>
                            }
                            <Blazor.Server.UI.Pages.Visitors.CheckinComponent.CheckinViewComponent TRequest="request"></Blazor.Server.UI.Pages.Visitors.CheckinComponent.CheckinViewComponent>
                        </MudTabPanel>
                        <MudTabPanel Text="@L["Check-out"]">
                            @if (_notfound)
                            {
                                <MudAlert Severity="MudBlazor.Severity.Error">@L["Not found visitor"]</MudAlert>
                            }
                            @if (_visitor is not null && _visitor.Status != VisitorStatus.PendingCheckout)
                            {
                                <MudAlert Severity="MudBlazor.Severity.Error">@L[string.Format("Visitor current status is {0}",_visitor.Status)]</MudAlert>
                            }
                            <Blazor.Server.UI.Pages.Visitors.CheckinComponent.CheckoutViewComponent TRequest="request"></Blazor.Server.UI.Pages.Visitors.CheckinComponent.CheckoutViewComponent>
                        </MudTabPanel>
                    </MudTabs>



                </div>
            </MudItem>

        </MudGrid>
    </ChildContent>
    <ErrorContent>
        <CustomError Exception="context"></CustomError>
    </ErrorContent>
</ErrorBoundary>
@code {

    public string? Title { get; private set; }
    private bool _uploading;
    private bool _autoCheckin;
    private bool _notfound = false;
    private string _imgUri;
    private string _captionText;
    private string _decodedText;

    private VisitorDto? _visitor = new();
    [Inject]
    private ISender _mediator { get; set; } = default!;
    private CreateVisitorHistoryCommand request { get; set; } = new CreateVisitorHistoryCommand();
    FontCollection collection = new FontCollection();
    FontFamily sansFamily;
    Font captionFont;

    protected override Task OnInitializedAsync()
    {
        captionFont = SystemFonts.CreateFont("Arial", 23, FontStyle.Bold);
        Title = L["Check-in"];
        return base.OnInitializedAsync();
    }
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JS.InvokeVoidAsync("initalScanner", "my_camera", DotNetObjectReference.Create(this));
        }
        await base.OnAfterRenderAsync(firstRender);
    }
    private async Task TakePhoto(MouseEventArgs e)
    {
        await JS.InvokeVoidAsync("takeSnapshot", DotNetObjectReference.Create(this));
    }
    [JSInvokable]
    public async Task GetResult(string decodedText)
    {
        _decodedText = decodedText;
        _visitor = await _mediator.Send(new SearchVisitorQuery(decodedText));
        if (_visitor is null)
        {
            _notfound = true;
        }
        else
        {
            var visitorHistories = (await _mediator.Send(new GetByVisitorIdVisitorHistoriesQuery(_visitor.Id))).ToList();
            request = new CreateVisitorHistoryCommand()
                {
                    CurrentStatus = _visitor.Status,
                    PassCode = _visitor.PassCode,
                    QrCode = _visitor.QrCode,
                    SiteId = _visitor.SiteId,
                    CompanionCount = _visitor.CompanionCount,
                    VisitEmployee = _visitor.Employee,
                    Avatar = _visitor.Avatar,
                    CompanyName = _visitor.CompanyName,
                    VisitorId = _visitor.Id,
                    Visitor = _visitor.Name,
                    LicensePlateNumber = _visitor.LicensePlateNumber,
                    Companions = _visitor.Companions,
                    CheckinPointId = null,
                    Histories = visitorHistories

                };

        }
        StateHasChanged();
    }
    [JSInvokable]
    public Task ClearResult()
    {
        //_decodedText = "";
        //StateHasChanged();
        return Task.CompletedTask;
    }
    [JSInvokable]
    public Task ProcessImage(string imageString)
    {
        byte[] imageData = Convert.FromBase64String(imageString.Split(',')[1]);
        _captionText = "adGaLOJWKjjb";
        //Do image processing here

        var drawingOptions = new DrawingOptions()
            {
                GraphicsOptions = new GraphicsOptions()
                {

                }
            };
        var textOptions = new TextOptions(captionFont)
            {
                TextAlignment = TextAlignment.Center,
                HorizontalAlignment = SixLabors.Fonts.HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Bottom,
            };

        using (var image = Image.Load(imageData))
        {
            var width = image.Width;
            var height = image.Height + 50;
            var resizeOptions = new ResizeOptions()
                {
                    Mode = SixLabors.ImageSharp.Processing.ResizeMode.Pad,
                    PadColor = SixLabors.ImageSharp.Color.Black,
                    Size = new SixLabors.ImageSharp.Size(width, height),
                    Position = AnchorPositionMode.TopLeft

                };
            image.Mutate(x => x
                .Flip(FlipMode.Horizontal) //To match mirrored webcam image
                .Resize(resizeOptions)
                .Fill(SixLabors.ImageSharp.Color.ParseHex("0008"), new RectangularPolygon(0, 240, 320, 50)) //Set footer bar for caption
                .DrawText(drawingOptions, _captionText, captionFont, SixLabors.ImageSharp.Color.White, new PointF(75, 252)) //center in footer bar)
            );
            _imgUri = image.ToBase64String(JpegFormat.Instance);
        }
        return Task.CompletedTask;
    }



}
